package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishVO>> listDishByCategory(Long categoryId) {
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品

        // 构建 redis缓存 中的key
        String key = "dish:" + dish.getCategoryId();
        // 根据key在redis中取数据
        List<DishVO> redisList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        // 判断是否成功取出数据
        if (redisList != null) {
            // 缓存中有数据 直接返回
            return Result.success(redisList);
        }

        // 缓存中没有数据 查数据库 并放入缓存
        List<DishVO> dishes = dishService.listDishByCategoryId(dish);
        // 将查询出的数据 放入缓存
        redisTemplate.opsForValue().set(key, dishes);
        return Result.success(dishes);
    }
}
